<script setup>
import {ElMessage} from 'element-plus'
import {Lock, Message} from '@element-plus/icons-vue'
import {onBeforeMount, onBeforeUnmount, onMounted, ref, watch} from 'vue';
import {useRouter} from 'vue-router'
import {codeService, getUserInfoService, loginService, registerService, resetPwdService} from "@/api/user.js";
import {getSchoolNamesService} from "@/api/school.js";
import {useTokenStore} from "@/stores/token.js";
import { useUserIdStore} from "@/stores/userInfo.js";

const route = useRouter()
const title = ref('') //标签标题

//定义数据模型
const registerData = ref({
  email: "",
  schoolId: "",
  schoolName: "",
  password: "",
  rePassword: "",
  captcha: "",
  loginMethods: 2 //0-注册 1-邮箱登录 2-密码登录 3-重置密码
})
const countingDown = ref(false)
const countdownSeconds = ref(60)
const countdownText = ref('获取验证码')
const isRemember = ref(false) //是否开启自动登录

// 清空数据
const clearRegisterData = () => {
  registerData.value = {
    email: "",
    schoolId: "",
    schoolName: "",
    password: "",
    rePassword: "",
    captcha: "",
    sName: ""
  }
}
// 修改登录注册方法
const changeMethods = (value) => {
  registerData.value.loginMethods = value
}
//校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerData.value.password) {
    callback(new Error('两次密码不一致'))
  } else {
    callback()
  }
}

// 校验学校是否开通服务
const checkSchool = async (value) => {
  let result = await getSchoolNamesService("")
  let schoolNames = result.data.map(items => items.schoolName)
  for (let i = 0; i < schoolNames.length; i++) {
    if (value === schoolNames[i]) {
      return true
    }
  }
  return false
}

//定义表单校验规则
const rules = ref({
  email: [
    {required: true, message: "请输入邮箱号", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        const pattern = /^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+\.)+[a-zA-Z]{2,}$/;
        if (!pattern.test(value)) {
          callback(new Error('邮箱格式不正确'))
        } else {
          callback()
        }
      }, trigger: "blur"
    }
  ],
  schoolName: [
    {required: true, message: "请输入学校名称", trigger: "blur"},
    {
      validator: async (rule, value, callback) => {
        const pattern = /[\u4e00-\u9fff]+/g;
        if (!pattern.test(value)) {
          callback(new Error('学校名称格式不正确'))
        } else if (!await checkSchool(value)) {
          callback(new Error('该学校还尚未开通服务'))
        } else {
          callback()
        }
      },
      trigger: "blur"
    }
  ],
  captcha: [
    {required: true, message: "请输入4位验证码", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        const pattern = /^\d{4}$/;
        if (!pattern.test(value)) {
          callback(new Error('验证码格式不正确'))
        } else {
          callback()
        }
      }
    }
  ],
  password: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {min: 5, max: 16, message: "密码为5~16位数字或字母", trigger: "blur"}
  ],
  rePassword: [
    {validator: checkRePassword, trigger: "blur"}
  ]
})

//获取验证码
const sendCaptcha = () => {
  codeService(registerData.value.email, registerData.value.loginMethods)
  countingDown.value = true
  countdownText.value = `${countdownSeconds.value} 秒后重新获取`
  startCountdown()
  ElMessage.success("验证码发送成功");
}

// 在 setup 函数内
let countdownInterval;
onMounted(() => {
  title.value = route.currentRoute.value.meta.title;
  document.title = title.value;

  // 页面加载时从 localStorage 加载倒计时状态
  const persistedCountdownState = JSON.parse(localStorage.getItem('countdownState'));
  if (persistedCountdownState) {
    countingDown.value = persistedCountdownState.countingDown;
    countdownSeconds.value = persistedCountdownState.secondsRemaining;
    // 如果仍在倒计时，则启动倒计时器
    if (countingDown.value) {
      startCountdown();
    }
  }

  // 从 localStorage 恢复用户账号密码
  const rememberedUserEmail = localStorage.getItem('rememberedUserEmail');
  const rememberedUserPwd = localStorage.getItem('rememberedUserPwd');
  if (rememberedUserEmail && rememberedUserPwd) {
    registerData.value.email = rememberedUserEmail;
    registerData.value.password = rememberedUserPwd;
    isRemember.value = true;
  }
});

watch(()=>({email: registerData.value.email,password: registerData.value.password}), (newValue,oldValue) => {
  if (localStorage.getItem("rememberedUserEmail")){
    localStorage.setItem("rememberedUserEmail", newValue.email);
  }
  if (localStorage.getItem("rememberedUserPwd")){
    localStorage.setItem("rememberedUserPwd", newValue.password);
  }
})


// 开始倒计时
const startCountdown = () => {
  countdownInterval = setInterval(() => {
    countdownSeconds.value--;
    countdownText.value = `${countdownSeconds.value} 秒后重新获取`;
    updateLocalStorage(); // 每次更新倒计时都同步到 localStorage

    if (countdownSeconds.value <= 0) {
      clearInterval(countdownInterval);
      countdownSeconds.value = 60;
      countdownText.value = '获取验证码';
      countingDown.value = false;
      updateLocalStorage(); // 倒计时结束时也同步到 localStorage
    }
  }, 1000);
}

// 更新本地存储中的倒计时状态
const updateLocalStorage = () => {
  localStorage.setItem(
      'countdownState',
      JSON.stringify({
        countingDown: countingDown.value,
        secondsRemaining: countdownSeconds.value,
      })
  );
};


const tokenStore = useTokenStore();
const userIdStore = useUserIdStore();
//登录
const login = async () => {
  let result = await loginService(registerData.value);
  tokenStore.setToken(result.data);
  ElMessage.success("登录成功");
  let res = await getUserInfoService()
  userIdStore.setUserId(res.data.id);
  route.push('/')
}


//注册
const register = async () => {
  if (!await checkSchool(registerData.value.schoolName)) {
    ElMessage.error("该学校尚未开通服务");
    return;
  }
  await registerService(registerData.value);
  ElMessage.success("注册成功");
  clearRegisterData();
  registerData.value.loginMethods = 2;
}

const fetchSchoolSuggestions = async (queryString, cb) => {
  let result = await getSchoolNamesService(queryString);
  const suggestions = result.data.map(school => ({
    value: school.schoolName,
    label: school.id,
  }));
  // 调用cb函数将建议数据传递给el-autocomplete组件
  cb(suggestions);
}

function handleSelect(item) {
  // 用户选择学校时触发的事件处理函数
  registerData.value.schoolId = item.label;
  registerData.value.schoolName.value = item.value;
}

const resetPwd = async () => {
  await resetPwdService(registerData.value)
  ElMessage.success("重置密码成功");
  clearRegisterData();
  isRemember.value = false;
  registerData.value.loginMethods = 2;
}
const handleKeyUp = (event) => {
  event.preventDefault();
  event.stopPropagation();
  if (event.key === "Enter") {
    if (registerData.value.loginMethods === 0) {
      register();
    } else if (registerData.value.loginMethods === 1 || registerData.value.loginMethods === 2) {
      login();
    } else if (registerData.value.loginMethods === 3) {
      resetPwd();
    }
  }
}


window.addEventListener('keyup', handleKeyUp)
// 在组件卸载前清除定时器并保存状态
onBeforeUnmount(() => {
  clearInterval(countdownInterval);
  updateLocalStorage();
  window.removeEventListener('keyup', handleKeyUp)
});


const rememberPwd = () => {
  if (isRemember.value) {
    //取消勾选
    localStorage.removeItem("rememberedUserEmail")
    localStorage.removeItem("rememberedUserPwd")
  } else {
    //已勾选
    localStorage.setItem("rememberedUserEmail", registerData.value.email)
    localStorage.setItem("rememberedUserPwd", registerData.value.password)
  }
}
</script>

<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-if="registerData.loginMethods===0" :model="registerData"
               :rules="rules">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="email">
          <el-input :prefix-icon="Message" placeholder="请输入邮箱" v-model="registerData.email"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                    v-model="registerData.rePassword"></el-input>
        </el-form-item>
        <el-form-item prop="schoolName">
          <el-autocomplete
              v-model="registerData.schoolName"
              :fetch-suggestions="fetchSchoolSuggestions"
              placeholder="学校名称"
              @select="handleSelect"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="captcha">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input placeholder="请输入验证码" v-model="registerData.captcha"></el-input>
            </el-col>
            <el-col :span="8">
              <el-button v-if="!countingDown" type="primary" @click="sendCaptcha()" style="margin-left: 30px">
                获取验证码
              </el-button>
              <el-button v-else type="primary" disabled>
                {{ countdownText }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <p class="hint">温馨提示: 学校绑定后将无法修改，请谨慎选择</p>
          </div>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="register">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="clearRegisterData(); changeMethods(2)">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 邮箱登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else-if="registerData.loginMethods===1"
               :model="registerData" :rules="rules">
        <el-form-item>
          <h1>邮箱登录</h1>
        </el-form-item>
        <el-form-item prop="email">
          <el-input :prefix-icon="Message" placeholder="请输入邮箱" v-model="registerData.email"></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input placeholder="请输入验证码" v-model="registerData.captcha"></el-input>
            </el-col>
            <el-col :span="8">
              <el-button v-if="!countingDown" type="primary" @click="sendCaptcha()" style="margin-left: 30px">
                获取验证码
              </el-button>
              <el-button v-else type="primary" disabled>
                {{ countdownText }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <!--            <el-checkbox>记住我</el-checkbox>-->
            <div></div>
            <el-link type="primary" :underline="false" @click="changeMethods(2)" style="margin-left: 35%">密码登录
            </el-link>
            <el-link type="primary" :underline="false" @click="clearRegisterData();changeMethods(3)">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login()">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="clearRegisterData() ,changeMethods(0)">
            没有账号? 注册一个
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 密码登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else-if="registerData.loginMethods===2"
               :model="registerData" :rules="rules">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="email">
          <el-input :prefix-icon="Message" placeholder="请输入邮箱" v-model="registerData.email"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox v-model="isRemember" @click="rememberPwd()">记住我</el-checkbox>
            <el-link type="primary" :underline="false" @click="changeMethods(1)" style="margin-left: 35%">邮箱登录
            </el-link>
            <el-link type="primary" :underline="false" @click="clearRegisterData(); changeMethods(3)">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login()">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="clearRegisterData() ;changeMethods(0)">
            没有账号? 注册一个
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 忘记密码表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else-if="registerData.loginMethods===3"
               :model="registerData" :rules="rules">
        <el-form-item>
          <h1>重置密码</h1>
        </el-form-item>
        <el-form-item prop="email">
          <el-input :prefix-icon="Message" placeholder="请输入邮箱" v-model="registerData.email"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入新密码"
                    v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次新密码"
                    v-model="registerData.rePassword"></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input placeholder="请输入验证码" v-model="registerData.captcha"></el-input>
            </el-col>
            <el-col :span="8">
              <el-button v-if="!countingDown" type="primary" @click="sendCaptcha()" style="margin-left: 30px">
                获取验证码
              </el-button>
              <el-button v-else type="primary" disabled>
                {{ countdownText }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <p class="hint">温馨提示: 请保管好您的账号密码</p>
          </div>
        </el-form-item>
        <!-- 重置按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="resetPwd()">确认重置密码</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="clearRegisterData(); changeMethods(2)">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    //background: url('@/assets/') no-repeat 60% center / 240px auto,
    //url('@/assets/') no-repeat center / cover;
    //border-radius: 0 20px 20px 0;
    background: url('@/assets/logo2.png') no-repeat center;
    background-blend-mode: overlay;
    background-size: 70%;
    //background-size:
    //    8em 8em, 8em 8em, cover;
    //border-radius: 0 20px 20px 0;
    margin-bottom: 5px;
    //border-radius: 10px;
    border-right: 1px solid rgb(0, 0, 0, 0.2);
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;

      .hint {
        font-size: 12px;
        color: #999;
        margin-top: -15px;;
        margin-bottom: -15px;
      }
    }
  }
}

</style>
